﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Entities;
/// <summary>
/// Summary description for ShoppingCard
/// </summary>
public class ShoppingCard
{
    private Dictionary<Product, int> list;
    public Dictionary<Product, int> Cards
    {
        get
        {
            return list;
        }

        set
        {
            list = value;
        }
    }

    private Decimal total;

    public Decimal Total
    {
        get
        {
            Dictionary<Product, int>.KeyCollection plist = list.Keys;
            total = 0;
            foreach (Product p in plist)
            {
                total += Convert.ToDecimal(p.ProductPrice) * list[p];
            }
            return total;
        }
    }

    public ShoppingCard()
    {
        list = new Dictionary<Product, int>();
    }

    public void AddProduct(Product p)
    {
        if (Contain(p))
        {
            int count = list[getProduct(p)] + 1;
            list[getProduct(p)] = count;
        }
        else
        {
            list.Add(p, 1);
        }
    }

    public void update(Product p, int Quantily)
    {
        if (Contain(p))
        {
            list[getProduct(p)] = Quantily;
        }
        else
        {
            list.Add(p, Quantily);
        }
    }

    public void RemoveProduct(Product p)
    {
        if (Contain(p))
            list.Remove(getProduct(p));
    }


    private Product getProduct(Product p)
    {
        Dictionary<Product, int>.KeyCollection pList = list.Keys;
        foreach (Product item in pList)
        {
            if (item.ProductID == p.ProductID)
                return item;
        }
        return null;
    }

    private bool Contain(Product p)
    {
        Dictionary<Product, int>.KeyCollection pList = list.Keys;
        //for (int i = 0; i < list.Keys.Count; i++)
        //{
        //    if (pList.ElementAt(i).ProductID == p.ProductID)
        //        return true;
        //}

        foreach (Product item in pList)
        {
            if (item.ProductID == p.ProductID)
                return true;
        }
        return false;
    }
}